//
//  CLDocumentModel.m
//  chanlin
//
//  Created by Ryan on 14-11-16.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLDocumentModel.h"

#import "INHtmlElement.h"
#import "CLGloble.h"
#import "INHtmlElementUtil.h"


@implementation CLDocumentModel

- (void)dealloc{
    if(self.framesetter!=NULL){
        CFRelease(self.framesetter);
    }
}

- (BOOL)isReady{
    return !!self.entity;
}

- (void)linkElement:(CLDocEntity *)entity{
//    self.attributeString=[[NSMutableAttributedString alloc] init];
//    __weak typeof(self) me=self;
//    [entity.elements enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        INHtmlElement *element=obj;
//        if(element.type==HtmlElementTypeText){
//            element.textRange=NSMakeRange([self.attributeString length], element.strValue.length+1);
//            NSMutableAttributedString *attrstr=[element attributedStringWithContent];
//            //element.textAttributedString=attrstr;
//            //[attrstr appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
//            //[me _fitoutParagraph4Text2:element];
//            
//            
//            
//            [me.attributeString appendAttributedString :attrstr];
//            // 换行
//            
//           // [me _fitoutParagraph4Text:me.attributeString];
//        }else if(element.type==HtmlElementTypeImage){
//            element.noteAttr=[me imgNoteString:element.imgNote
//                                     withWidth:I_DOC_CONTENT_WIDTH
//                                          font:[INHtmlElementUtil sharedInstance].altFont
//                                     lineSpace:[INHtmlElementUtil sharedInstance].altLineSpace];
//        }
//    }];
//    
//    [self _fitoutParagraph4Text:self.attributeString];
    self.entity=entity;
//    self.framesetter=CTFramesetterCreateWithAttributedString((__bridge  CFAttributedStringRef)self.attributeString);
//    [self doSuggessFrame];
//    [self doTitleAttributeString];
}

- (NSString *)sourceAndTime{
    NSString *time=[[INHtmlElementUtil sharedInstance] timeFormateFrom:self.entity.time];
    NSString *source=self.entity.source;
    NSString *sourceAndTime=[NSString stringWithFormat:@"%@  %@",_isStrNULL(source)?@"":source,_isStrNULL(time)?@"":time];
    return sourceAndTime;
}

- (void)setFramesetter:(CTFramesetterRef)aframesetter{
    if(_framesetter){
        CFRelease(_framesetter);
        _framesetter=NULL;
    }
    _framesetter=aframesetter;
    CFRetain(aframesetter);
}

- (void)doTitleAttributeString{
    if(_isStrNULL(self.entity.title)) return;
    NSMutableAttributedString *mbstring=[[NSMutableAttributedString alloc] initWithString:self.entity.title];
    int length=(int)[self.entity.title length];
    // 字体Arial-BoldMT STHeitiSC-Light
    //CTFontRef font=CTFontCreateWithName(CFSTR("HelveticaNeue-Medium"), 22, NULL);
    UIFont *font=[UIFont fontWithName:@"HelveticaNeue-Medium" size:22.f];
   // [mbstring addAttribute:(id)kCTFontAttributeName value:(__bridge id)font range:NSMakeRange(0, length)];
    [mbstring addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, length)];
    //CFRelease(font);
    
    // 字体颜色
    //CGColorRef color=[UIColor blackColor].CGColor;
        //[mbstring addAttribute:(id)kCTForegroundColorAttributeName value:(__bridge id)color range:NSMakeRange(0, length)];
    [mbstring addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length)];
    // 行间距
//    float lightSpacing=3.0f;
//    // 段落对其方式
//    CTTextAlignment textAlignment = kCTTextAlignmentLeft;
    
//    CTParagraphStyleSetting paraStyles[3] = {
//        
//        {.spec = kCTParagraphStyleSpecifierMinimumLineSpacing,.valueSize = sizeof(float), .value = &lightSpacing},
//        
//        {.spec = kCTParagraphStyleSpecifierMaximumLineSpacing,.valueSize = sizeof(float), .value = &lightSpacing},
//        
//        {.spec = kCTParagraphStyleSpecifierAlignment,.valueSize = sizeof(CTTextAlignment), .value = &textAlignment}
//    };
    
   
    
   // CTParagraphStyleRef pStyle=CTParagraphStyleCreate(paraStyles, 3);
    
    NSMutableParagraphStyle *style=[[NSMutableParagraphStyle alloc] init];
    style.alignment=NSTextAlignmentLeft;
    style.firstLineHeadIndent=0.f;
    style.lineSpacing=3.f;
    
    
    //NSParagraphStyleAttributeName
    //[mbstring addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)pStyle range:NSMakeRange(0, length)];
    [mbstring addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, length)];
    //CFRelease(pStyle);
    self.titleAttributeStr=mbstring;
}
- (void)_fitoutParagraph4Text2:(INHtmlElement *)element {
    NSMutableParagraphStyle *style=[[NSMutableParagraphStyle alloc] init];
    style.alignment=NSTextAlignmentJustified;
    style.lineBreakMode=NSLineBreakByWordWrapping;
   // style.minimumLineHeight=element.attributeEntitys
    style.lineSpacing=16.f;
   
    [element.textAttributedString addAttribute:NSParagraphStyleAttributeName
                                         value:style
                                         range:NSMakeRange(0, element.textAttributedString.length)];
}


- (void)_fitoutParagraph4Text:(NSMutableAttributedString *)attributeString{
    // 对齐方式
    CTParagraphStyleSetting alignmentStyle;
    CTTextAlignment alignment = kCTJustifiedTextAlignment;
    alignmentStyle.spec=kCTParagraphStyleSpecifierAlignment;
    alignmentStyle.valueSize=sizeof(alignment);
    alignmentStyle.value=&alignment;
    //换行模式
    CTParagraphStyleSetting lineBreakMode;
    CTLineBreakMode lineBreak = kCTLineBreakByWordWrapping;
    lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;
    lineBreakMode.value = &lineBreak;
    lineBreakMode.valueSize = sizeof(CTLineBreakMode);
    //行距
    CGFloat _linespace = [INHtmlElementUtil sharedInstance].textLineSpace;
    //
    CTParagraphStyleSetting lineSpaceSettingAdj;
    lineSpaceSettingAdj.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;
    lineSpaceSettingAdj.value = &_linespace;
    lineSpaceSettingAdj.valueSize = sizeof(float);
    // 最小行距
    CTParagraphStyleSetting lineSpaceSettingMin;
    lineSpaceSettingMin.spec = kCTParagraphStyleSpecifierMinimumLineSpacing;
    lineSpaceSettingMin.value = &_linespace;
    lineSpaceSettingMin.valueSize = sizeof(float);
    // 最大行距
    CTParagraphStyleSetting lineSpaceSettingMax;
    lineSpaceSettingMax.spec = kCTParagraphStyleSpecifierMaximumLineSpacing;
    lineSpaceSettingMax.value = &_linespace;
    lineSpaceSettingMax.valueSize = sizeof(float);
    
    CTParagraphStyleSetting lineSpaceSettingSpacing;
    lineSpaceSettingMax.spec = kCTParagraphStyleSpecifierLineSpacing;
    lineSpaceSettingMax.value = &_linespace;
    lineSpaceSettingMax.valueSize = sizeof(float);
    
    //组合设置
    CTParagraphStyleSetting settings[] = {
        alignmentStyle,
        lineBreakMode,
        lineSpaceSettingAdj,
        lineSpaceSettingMin,
        lineSpaceSettingMax,
        lineSpaceSettingSpacing
        
    };
    //通过设置项产生段落样式对象
    CTParagraphStyleRef style = CTParagraphStyleCreate(settings, 6);
    [attributeString addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)style range:NSMakeRange(0, attributeString.length)];
    
    NSMutableParagraphStyle *nsstyle=[[NSMutableParagraphStyle alloc] init];
    nsstyle.alignment=NSTextAlignmentJustified;
    nsstyle.firstLineHeadIndent=0.f;
    nsstyle.lineSpacing=[INHtmlElementUtil sharedInstance].textLineSpace;
    nsstyle.lineBreakMode=NSLineBreakByWordWrapping;
    
    [attributeString addAttribute:NSParagraphStyleAttributeName value:nsstyle range:NSMakeRange(0, attributeString.length)];
    
    
}

- (NSMutableAttributedString *)imgNoteString:(NSString *)str withWidth:(float)width font:(UIFont *)font lineSpace:(float)lineSpace{
    if(_isStrNULL(str))return nil;
    
    NSMutableAttributedString *mbstring=[[NSMutableAttributedString alloc] initWithString:str];
    int length=[str length];
    //NSLog(@"%f--%f",self.font.pointSize);
    // 字体
    CTFontRef reffont=CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);
    [mbstring addAttribute:(id)kCTFontAttributeName value:(__bridge id)reffont range:NSMakeRange(0, length)];
    CFRelease(reffont);
    
    
    [mbstring addAttribute:NSForegroundColorAttributeName value:RGB(0x55, 0x57, 0x5e) range:NSMakeRange(0, length)];
    
    float lightSpacing=lineSpace;
    if(lightSpacing==0){
        lightSpacing=font.lineHeight-font.pointSize+1;
    }
    
    // 段落对其方式
    CTTextAlignment textAlignment = kCTTextAlignmentLeft;
    
    CTParagraphStyleRef pStyle=NULL;
    
    if(lightSpacing!=0){
        CTParagraphStyleSetting paraStyles[3] = {
            
            {.spec = kCTParagraphStyleSpecifierMinimumLineSpacing,.valueSize = sizeof(float), .value = &lightSpacing},
            
            {.spec = kCTParagraphStyleSpecifierMaximumLineSpacing,.valueSize = sizeof(float), .value = &lightSpacing},
            
            {.spec = kCTParagraphStyleSpecifierAlignment,.valueSize = sizeof(CTTextAlignment), .value = &textAlignment}
        };
        
        pStyle=CTParagraphStyleCreate(paraStyles, 3);
        
    }else{
        CTParagraphStyleSetting paraStyles[1] = {
            {.spec = kCTParagraphStyleSpecifierAlignment,.valueSize = sizeof(CTTextAlignment), .value = &textAlignment}
        };
        
        pStyle=CTParagraphStyleCreate(paraStyles, 3);
    }
    
    [mbstring addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)pStyle range:NSMakeRange(0, length)];
    
    CFRelease(pStyle);
    
//    CTFramesetterRef framesetter=CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)mbstring);
//    
//    CGSize size=CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, length), NULL, CGSizeMake(width, CGFLOAT_MAX), NULL);
//    
//    CFRelease(framesetter);
    
    return mbstring;
}

- (void)doSuggessFrame{
    __weak typeof(self) me=self;
    [self.entity.elements enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        INHtmlElement *element=obj;
        if(element.type==HtmlElementTypeText){
            CGSize size=[me suggestFrameSize:element.textRange];
            element.textHeight=ceilf(size.height);
            element.cellHeight=ceilf(size.height)+28.f;
        }else if(element.type==HtmlElementTypeImage){
            CGSize size=[me suggestImgFrameSize:element.noteAttr];
            element.noteHeight=ceilf(size.height);
//            if(element.imgHeight==0||element.imgWidth==0 || isnan(element.imgHeight) || isnan(element.imgWidth)){
//                element.imgWidth=290;
//                element.imgHeight=300.f;
//            }else{
//                element.imgHeight=(element.imgHeight/element.imgWidth)*I_DOC_CONTENT_WIDTH;
//            }
            
            element.cellHeight=22.0f+12.0f+element.imgHeight+6.0f+element.noteHeight;
        }else if(element.type==HtmlElementTypeGallery){
            
            //element.imgHeight=164.f;
            //element.cellHeight=22.0f+12.0f+element.imgHeight+6.0f;
            element.cellHeight=180.f;
        }
    }];

}

- (CGSize )suggestImgFrameSize:(NSAttributedString *)string{
    if(!string) return CGSizeZero;
    CTFramesetterRef framesetter=CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);
    
    CGSize size=CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, string.length), NULL, CGSizeMake(I_DOC_CONTENT_WIDTH, CGFLOAT_MAX), NULL);
    
    CFRelease(framesetter);
    
    return size;
}

- (CGSize )suggestTextFrameSize:(NSAttributedString *)string{
    if(!string) return CGSizeZero;
    
   
    CTFramesetterRef framesetter=CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)string);
    
    CGSize size=CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, string.length), NULL, CGSizeMake(I_DOC_CONTENT_WIDTH, CGFLOAT_MAX), NULL);
    
    CFRelease(framesetter);
    
    return size;
}

- (CGSize )suggestFrameSize:(NSRange )stringRange{
    
    CGSize size=CTFramesetterSuggestFrameSizeWithConstraints(self.framesetter,
                                                             CFRangeMake(stringRange.location, stringRange.length),
                                                             NULL,
                                                             CGSizeMake(I_DOC_CONTENT_WIDTH, CGFLOAT_MAX),
                                                             NULL);
    return size;
    
}
@end
